<template>
	<div class="new">
		<h2>
			<el-page-header @back="$utils.goBack()" :content="$route.query.id ? '更新课程' :' 发布课程'">
			</el-page-header>
		</h2>
		<el-divider></el-divider>
		<el-container>
			<el-main>
				<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
					
					<el-form-item label="课程名称" prop="courseTitle">
						<el-input clearable v-model="ruleForm.courseTitle" placeholder="请输入课程名称"></el-input>
					</el-form-item>
					
					<el-form-item label="课程分类" prop="courseClass">
						<el-select @change="setDropClassId" v-model="ruleForm.courseClass" placeholder="请选择课程分类">
							<el-option v-for="(item,index) in classDataGetter" :label="item.classTitle" :value="item.classTitle"></el-option>
						</el-select>
					</el-form-item>
					
					<el-form-item label="课程介绍" prop="courseDesc">
						<el-input autosize type="textarea" v-model="ruleForm.courseDesc"></el-input>
					</el-form-item>
					
					<el-form-item label="课程封面图">
						<el-upload
							class="avatar-uploader"
							action="http://upload.qiniu.com/"
							:show-file-list="false"
							:on-success="handleAvatarSuccess"
							:data="UploadFileData"
							:before-upload="beforeAvatarUpload">
								<div class="el-upload__tip" slot="tip">Tips: 图片不能超过1Mb</div>
								<img v-if="ruleForm.courseImageUrl" :src="ruleForm.courseImageUrl" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</el-form-item>
					
					<el-form-item label="是否免费" prop="courseCharge">
						<el-select :disabled="$route.query.id ? 'disabled' : false " v-model="ruleForm.courseCharge" placeholder="请选择是否免费">
							<el-option label="收费" value="收费"></el-option>
							<el-option label="免费" value="免费"></el-option>
						</el-select>
						<br>
						<el-link type="danger" :underline="false">Tips: 课程是否收费一旦确定不允许修改</el-link>
					</el-form-item>
					
					<el-form-item label="课程原价" prop="coursePrice">
						<el-input clearable v-model.number="ruleForm.coursePrice" type="number" placeholder="请设置课程价格"></el-input>
					</el-form-item>
					
					<el-form-item label="发布时间" required>
						<el-col :span="11">
							<el-form-item >
								<el-date-picker
									:disabled="$route.query.id ? 'disabled' : false "
									type="date"
									placeholder="选择日期"
									v-model="ruleForm.courseDate"
									value-format="yyyy-MM-dd"
									@change="getTime"
									style="width: 100%;"></el-date-picker>
							</el-form-item>
							
							<el-link type="danger" :underline="false">Tips: 课程发布时间一旦确定不允许修改</el-link>
						</el-col>
					</el-form-item>
					
					<el-form-item label="课程难易" prop="courseResource">
						<el-radio-group v-model="ruleForm.courseResource">
							<el-radio label="初级"></el-radio>
							<el-radio label="初中级"></el-radio>
							<el-radio label="中级"></el-radio>
							<el-radio label="中高级"></el-radio>
							<el-radio label="高级"></el-radio>
							<el-radio label="高级以上"></el-radio>
						</el-radio-group>
					</el-form-item>
					
					<el-form-item>
						<el-button v-if="$route.query.id" :loading="ShowLoading" type="primary" @click="UpdateForm('ruleForm')">更新课程</el-button>
						<el-button v-else type="primary" :loading="ShowLoading" @click="submitForm('ruleForm')">创建课程</el-button>
						
						
						<el-button v-if="!$route.query.id" @click="resetForm('ruleForm')">重置</el-button>
					</el-form-item>
					
				</el-form>
			</el-main>
		</el-container>
		
	</div>
</template>

<script lang="ts">
	import { Vue, Component } from "vue-property-decorator"
	import { State, Getter, Action, Mutation } from 'vuex-class'
	
	@Component
	export default class NewComponents extends Vue {
		private ShowLoading:boolean = false;
		// 需要提交给后端的数据
		public ruleForm:Object = {
			courseTitle: null,
			courseCharge: null,
			courseImageUrl: null,
			courseClass: null,
			courseClassId: null,
			coursePrice: 0,
			courseDate: null,
			courseResource: null,
			courseDesc: null
		};
		// 表单验证规则
		public rules:Object = {
			courseTitle: [
					{ required: true, message: '请输入课程名称', trigger: 'blur' },
					{ min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }
			],
			courseClass: [
				{ required: true, message: '请选择课程分类', trigger: 'blur' }
			],
			courseCharge: [
				{ required: true, message: '请选择是否免费', trigger: 'blur' }
			],
			coursePrice: [
				{ required: true, message: '请设置课程价格'},
				{ type: 'number', message: '价格必须为数字' }
			],
			courseDate: [
				{ type: 'date', required: true, message: '请选择发布日期' }
			],
			courseResource: [
				{ required: true, message: '请选择课程难易程度', trigger: 'change' }
			],
			courseDesc: [
				{ required: true, message: '请填写课程简介信息', trigger: 'blur' },
				{ min: 3, max: 200, message: '长度在 3 到 300 个字符', trigger: 'blur' }
			],
			courseImg: [
				{ required: true, message: '请选择封面图', trigger: 'blur' },
			]
		};
		// 上传图片需要发送给 七牛 的数据
		public UploadFileData:Object = {
			token: null, // token
			key: null    // key 上传到七牛的视频文件名
		};
		
		// 获取Vuex存储的分类数据
		@Getter('getClassList') classDataGetter;
		
		created () {
			if(this.$route.query.id) {
				this.getUpdateFormData();
			}
		}
		
		setDropClassId(vals) {
			this.classDataGetter.forEach((val,index) => {
				for (let item in val) {
					if (val[item] == vals) {
						this.ruleForm.courseClassId = val.objectId
					}
				}
			});
		}
		
		/**
		 * 获取对应id的数据
		 */
		public async getUpdateFormData (): void {
			let data = await this.$http.post({
				url: '/admin/getCourseInfo',
				params: { id: this.$route.query.id }
			});
			this.ruleForm = data.result;
		}
		
		/**
		 * 更新课程
		 */
		public async UpdateForm (formName): void {
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					this.ShowLoading = true;
					let data = await this.$http.post({
						url: '/admin/UpdateCourse',
						params: this.ruleForm
					});
					this.$confirm('课程信息修改成功！[ 确定 ] 继续修改课程信息，[ 返回 ] 返回所有课程查看更改', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '返回',
						type: 'warning'
					}).then(() => {
						this.ShowLoading = false
					}).catch(() => {
						this.$router.push({ name: 'all'})
					});
				} else {
					this.$notify.error({
						title: '错误',
						message: '请仔细检查必填项！'
					});
					return false;
				}
			})
		}
		
		// TODO 如果使用 async/await 请安装 babel-plugin-transform-runtime
		// TODO 参考地址：https://babeljs.io/docs/en/babel-plugin-transform-runtime/
		/**
		 * 创建课程的事件
		 */
		public async submitForm(formName): void {
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					let addStatus = await this.$http.post({
						url: '/admin/newCourse',
						params: this.ruleForm
					});
					this.$confirm('课程已经发布成功！[ 确定 ] 为课程添加更多的视频章节', '提示', {
						confirmButtonText: '确定',
						type: 'warning'
					}).then(() => {
						this.$router.push({ name: 'video', params: { id: addStatus.result.objectId } })
					})
					
				} else {
					this.$notify.error({
						title: '错误',
						message: '请仔细检查必填项！'
					});
					return false;
				}
			});
		}
		
		/**
		 * 格式化获取时间
		 */
		getTime(val) {
			const d = new Date(val);
			this.ruleForm.courseDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
		}
		
		/**
		 * 上传成功的事件回调
		 */
		handleAvatarSuccess(res, file) {
			this.ruleForm.courseImageUrl = `http://static.geekhelp.cn/${res.key}`;
			this.$notify({
				title: '成功',
				message: '文件上传成功，请勿刷新页面！',
				type: 'success'
			});
		}
		
		/**
		 * 上传之前对图片格式进行检查
		 * @param file
		 */
		public async beforeAvatarUpload(file) {
			const isJPG = file.type === 'image/jpeg';
			const isPNG = file.type === 'image/png';
			const isLt2M = file.size / 1024 / 1024 < 1;
			if(!isJPG && !isPNG) {
				this.$message.error('上传图片必须是JPG/PNG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 1MB!');
			}
			
			// 获取后端的token参数，赋值给 UploadFileData
			let token = await this.$http.post({ url: '/admin/token', params: {} });
			this.UploadFileData.token = token.result.token;
			this.UploadFileData.key = file.name;
			
			return (isJPG || isPNG) && isLt2M;
		}
		
		/**
		 * 重置表单的功能
		 * @param formName
		 */
		resetForm(formName) {
			this.$refs[formName].resetFields();
		}
	}
</script>

<style  lang="less">
	.el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
	.el-upload:hover {
		border-color: #409EFF;
	}
	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}
	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>